package org.soarsky.wealthchengdu.httpClient;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;


public class HttpClientExecutor
{		
	private static final int DEFAULT_MAX_CONNECTIONS = 5;	
	private static final int TIMEOUT = 5000;
    private static final int TIMEOUT_SOCKET = 5000;     
	
	private HttpClient					httpClient;

	/************ Singleton ***********/
	private static HttpClientExecutor	instance				= new HttpClientExecutor();

	private HttpClientExecutor()
	{			
		   HttpParams params = new BasicHttpParams();
           HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
           HttpProtocolParams.setContentCharset(params,
                           HTTP.DEFAULT_CONTENT_CHARSET);
           HttpProtocolParams.setUseExpectContinue(params, true);

           // 自定义三个timeout参数
           ConnManagerParams.setTimeout(params, 5000);
           ConnManagerParams.setMaxTotalConnections(params, DEFAULT_MAX_CONNECTIONS);
           HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
           HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);

           SchemeRegistry schReg = new SchemeRegistry();
           schReg.register(new Scheme("http", PlainSocketFactory
                           .getSocketFactory(), 80));
           schReg.register(new Scheme("https",
                           SSLSocketFactory.getSocketFactory(), 443));

           ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
                           params, schReg);

           httpClient = new DefaultHttpClient();           
	}

	public static HttpClientExecutor getInstance()
	{
		return instance;
	}

		
	/**
	 * 是否使用网关代理
	 * 
	 * @return
	 */
	/*private boolean isUserProxy()
	{
		int netType = NetworkInfoManager.getNetWorkType();
		return (netType == NetworkInfoManager.MPROXYTYPE_CMWAP || netType == NetworkInfoManager.MPROXYTYPE_UNIWAP || netType == NetworkInfoManager.MPROXYTYPE_WAP);
	}*/
	
	/**
	 * 创建自适应网络的 HttpPost
	 */
	private HttpPost newHttpPost(String destUrl) throws Exception
	{
		HttpPost httpPost = new HttpPost(destUrl);
		httpPost.setHeader("accept", "*/*");		
		
		/*if (isUserProxy())
		{			
			URL url = new URL(destUrl);
			String host = url.getHost();
			int port = url.getPort();
			String file = url.getFile(); // path+query
			
			String proxyUrl = NetworkInfoManager.getProxyUrl();
			if (proxyUrl == null)
			{
				return httpPost;
			}

			if (NetworkInfoManager.PROXY_CTWAP.equals(NetworkInfoManager.getProxyHost()))
			{   // 电信的wap代理				
				HttpHost proxyHost = new HttpHost(NetworkInfoManager.getProxyHost(), NetworkInfoManager.getProxyPort());
				httpPost.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxyHost);
			}
			else
			{ // 移动或联通的wap代理
				URL newUrl = new URL(proxyUrl + file);
				httpPost.setURI(newUrl.toURI());
				httpPost.setHeader("X-Online-Host", host + ":" + port);
			}
		}*/
		return httpPost;
	}


	/**
	 * 创建自适应网络的 HttpGet
	 */
	private HttpGet newHttpGet(String destUrl) throws Exception
	{
		HttpGet httpGet = new HttpGet(destUrl);
		httpGet.setHeader("accept", "*/*");	
		Log.e("url", destUrl);
		/*if (isUserProxy())
		{
			
			URL url = new URL(destUrl);
			String host = url.getHost();
			int port = url.getPort();
			String file = url.getFile(); // path+query
			
			String proxyUrl = NetworkInfoManager.getProxyUrl();
			if (proxyUrl == null)
			{
				return httpGet;
			}

			if (NetworkInfoManager.PROXY_CTWAP.equals(NetworkInfoManager.getProxyHost()))
			{   // 电信的wap代理				
				HttpHost proxyHost = new HttpHost(NetworkInfoManager.getProxyHost(), NetworkInfoManager.getProxyPort());
				httpGet.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxyHost);
			}
			else
			{   // 移动或联通的wap代理
				URL newUrl = new URL(proxyUrl + file);
				httpGet.setURI(newUrl.toURI());
				httpGet.setHeader("X-Online-Host", host + ":" + port);
			}
		}*/
		return httpGet;
	}

	/**
	 * 执行 POST 请求，POST 请求的服务器响应
	 */	
	public byte[] executePost(String url, List<NameValuePair> params)
	{
		byte[] resData = null;
		HttpPost httpPost = null;
		try
		{		
			if(!checkUrl(url))
				return null;
			httpPost = this.newHttpPost(url);
              Log.e("url", url+"list:"+params.toString());
			// 设置 post 参数
			if (params != null && params.size() > 0)
			{			
				httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			}
			
			// 发送请求
			HttpResponse httpResponse = httpClient.execute(httpPost);
			// 处理返回消息
			StatusLine statusLine = null;
			if (httpResponse == null || (statusLine = httpResponse.getStatusLine()) == null)
				return null;

			int responseCode = statusLine.getStatusCode();			

			if (responseCode == HttpStatus.SC_OK)
			{
				resData = EntityUtils.toByteArray(httpResponse.getEntity());
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			if (httpPost != null)
			{
				httpPost.abort();
			}			
		}
		return resData;
	}

	/**
	 * 执行 GET 请求，GET 请求的服务器响应为指定资源类型
	 */	
	public byte[] executeGet(String url) throws OutOfMemoryError
	{
		byte[] resData = null;
		HttpGet httpGet = null;
		try
		{
			if(!checkUrl(url))
				return null;
			
			httpGet = this.newHttpGet(url);
			// 发送请求
			HttpResponse httpResponse = httpClient.execute(httpGet);
			 Log.e("url  get", url);
			// 处理返回消息			
			StatusLine statusLine = null;
			if (httpResponse == null || (statusLine = httpResponse.getStatusLine()) == null)
				return null;

			int responseCode = statusLine.getStatusCode();			

			if (responseCode == HttpStatus.SC_OK)
			{
				resData = EntityUtils.toByteArray(httpResponse.getEntity());
			}
						
		}
		catch (Exception e)
		{			
			e.printStackTrace();
			if (httpGet != null)
			{
				httpGet.abort();
			}				
		}
		return resData;
	}
	
	/**
	 * 验证url的合法性
	 * @param url
	 * @return
	 */
	private static boolean checkUrl(String url) {
		return url.matches("^[a-zA-z]+://[^\\s]*$");
	}
}
